import logging
from logging.handlers import RotatingFileHandler
import sys
import io

# 强制标准输出使用 UTF-8
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')

def setup_logging() -> logging.Logger:
    logger = logging.getLogger()
    logger.setLevel(logging.DEBUG)

    for h in logger.handlers[:]:
        logger.removeHandler(h)

    fmt = logging.Formatter(
        "%(asctime)s [%(levelname)s] %(name)s:%(lineno)d - %(message)s"
    )

    # 控制台
    console = logging.StreamHandler(sys.stdout)
    console.setFormatter(fmt)
    console.setLevel(logging.DEBUG)
    logger.addHandler(console)

    # 文件
    file_handler = RotatingFileHandler(
        "app.log",
        encoding="utf-8",
        maxBytes=1024 * 1024,
        backupCount=3
    )
    file_handler.setFormatter(fmt)
    file_handler.setLevel(logging.DEBUG)
    logger.addHandler(file_handler)

    # 第三方库
    logging.getLogger("urllib3").setLevel(logging.DEBUG)
    logging.getLogger("requests").setLevel(logging.DEBUG)

    # FastMCP 兼容
    raw_console = logging.StreamHandler(sys.__stdout__)
    raw_console.setFormatter(fmt)
    raw_console.setLevel(logging.DEBUG)
    logger.addHandler(raw_console)

    return logger